<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            flex-direction: column;
            height: 90vh;
        }
        .login-form {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f5f5f5;
            border-radius: 5px;
        }
        .chat-room {
            display: none;
            flex: 1;
            flex-direction: column;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
        }
        .messages {
            flex: 1;
            padding: 10px;
            overflow-y: auto;
            background-color: #f9f9f9;
        }
        .message-input {
            display: flex;
            padding: 10px;
            background-color: #eee;
        }
        input, button {
            padding: 8px;
            margin: 5px 0;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .message {
            margin: 5px 0;
            padding: 8px;
            background-color: white;
            border-radius: 4px;
            word-break: break-word;
        }
        .system-message {
            color: #666;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="login-form" id="loginForm">
            <h2>加入聊天室</h2>
            <input type="text" id="roomId" placeholder="输入房间号" required>
            <input type="text" id="username" placeholder="输入你的昵称" required>
            <button id="joinBtn">加入房间</button>
        </div>

        <div class="chat-room" id="chatRoom">
            <div class="messages" id="messages"></div>
            <div class="message-input">
                <input type="text" id="messageInput" placeholder="输入消息..." disabled>
                <button id="sendBtn" disabled>发送</button>
            </div>
        </div>
    </div>

    <script>
        const roomIdInput = document.getElementById('roomId');
        const usernameInput = document.getElementById('username');
        const joinBtn = document.getElementById('joinBtn');
        const loginForm = document.getElementById('loginForm');
        const chatRoom = document.getElementById('chatRoom');
        const messagesContainer = document.getElementById('messages');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');

        let socket = null;
        let currentRoomId = '';
        let currentUsername = '';

        joinBtn.addEventListener('click', () => {
            const roomId = roomIdInput.value.trim();
            const username = usernameInput.value.trim();
            
            if (!roomId || !username) {
                alert('请输入房间号和昵称');
                return;
            }

            currentRoomId = roomId;
            currentUsername = username;
            
            connectWebSocket(roomId, username);
        });

        sendBtn.addEventListener('click', () => {
            sendMessage();
        });

        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        function connectWebSocket(roomId, username) {
            // WebSocket 连接地址
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const host = window.location.host; // 包含域名和端口

            // 构建 WebSocket 连接地址
            const wsUrl = `${protocol}//${host}/ws?roomId=${roomId}&username=${username}`;
            
            socket = new WebSocket(wsUrl);

            socket.onopen = () => {
                console.log('WebSocket 连接已建立');
                loginForm.style.display = 'none';
                chatRoom.style.display = 'flex';
                messageInput.disabled = false;
                sendBtn.disabled = false;
                
                addSystemMessage(`已连接到房间: ${roomId}`);
            };

            socket.onmessage = (event) => {
                const message = JSON.parse(event.data);
                displayMessage(message);
            };

            socket.onclose = () => {
                addSystemMessage('连接已断开');
                messageInput.disabled = true;
                sendBtn.disabled = true;
            };

            socket.onerror = (error) => {
                console.error('WebSocket 错误:', error);
                addSystemMessage('连接发生错误');
            };
        }

        function sendMessage() {
            const content = messageInput.value.trim();
            if (!content || !socket) return;

            const message = {
                type: 'chat',
                roomId: currentRoomId,
                username: currentUsername,
                content: content,
                timestamp: new Date().toISOString()
            };

            socket.send(JSON.stringify(message));
            messageInput.value = '';
        }

        function displayMessage(message) {
            const messageElement = document.createElement('div');
            messageElement.classList.add('message');
            
            if (message.type === 'system') {
                messageElement.classList.add('system-message');
                messageElement.textContent = message.content;
            } else {
                messageElement.innerHTML = `
                    <strong>${message.username}</strong>: ${message.content}
                    <div style="font-size: 0.8em; color: #666;">${new Date(message.timestamp).toLocaleTimeString()}</div>
                `;
            }
            
            messagesContainer.appendChild(messageElement);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        function addSystemMessage(text) {
            displayMessage({
                type: 'system',
                content: text,
                timestamp: new Date().toISOString()
            });
        }
    </script>
</body>
</html>